<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Logic\ArticleLogic;
use App\Middleware\AuthMiddleware;
use Exception;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Psr\Http\Message\ResponseInterface;

#[AutoController]
class ArticleController extends AbstractController
{

    /**
     * 资讯主页
     * @return ResponseInterface
     */
    public function homepage(): ResponseInterface
    {
        return $this->apiReturn(200, 'succ', ArticleLogic::getHomepageData());
    }

    /**
     * 获取文章栏目.
     */
    public function category(): ResponseInterface
    {
        $list = ArticleLogic::getCategoryList();
        return $this->apiReturn(200, 'succ', $list);
    }

    /**
     * 获取文章列表.
     */
    public function lists(): ResponseInterface
    {
        $input = $this->request->all();
        $res = ArticleLogic::getArticleList($input);
        return $this->apiReturn(200, 'succ', $res);
    }

    /**
     * 获取文章信息.
     */
    public function detail(): ResponseInterface
    {
        $this->parseToken();
        $userId = Context::get('userid', 0);
        $id = $this->request->input('id', 0);
        if (!intval($id)) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            $info = ArticleLogic::getDetail($userId, $id);
            return $this->apiReturn(200, 'succ', $info);
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 点赞喜欢
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function praise(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $id = $this->request->input('id', 0);
        if (!$id) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            ArticleLogic::praise($userid, $id);
            return $this->apiReturn(200, '操作成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 收藏
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function collect(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $id = $this->request->input('id', 0);
        if (!$id) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            ArticleLogic::collect($userid, $id);
            return $this->apiReturn(200, '操作成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

}
